package com.lambkit.devops;

import cn.hutool.Hutool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.alibaba.druid.pool.DruidDataSource;
import com.lambkit.core.Lambkit;
import com.lambkit.db.DbPool;
import com.lambkit.db.hutool.HutoolDb;
import com.lambkit.util.Printer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import static cn.hutool.db.dialect.DriverNamePool.DRIVER_SQLLITE3;

public class SqliteOpt {
	private static Log logger = Log.get(SqliteOpt.class);

	private Connection connection = null;
	private Statement statement = null;
	private String username = "sqlite";
	private String password = "sqlite";
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @describe: 设置连接
	 */
	public void setConnection(String dbfile) {
		try {
			// 声明驱动类型
			Class.forName("org.sqlite.JDBC");
			// 设置sqlite db文件存放基本目录
			if(dbfile.contains("%s")) {
				dbfile = String.format(dbfile, Lambkit.context().resourceService().getWebRootPath());
	    		Printer.print(this, "db", "jdbc.url: " + dbfile);
	    	}
			// 设置 sqlite文件路径，等同于mysql连接地址(jdbc:mysql://127.0.0.1:3306/test)
			String url = "jdbc:sqlite:" + dbfile;
			// 获取连接
			connection = DriverManager.getConnection(url, username, password);
			// 声明
			statement = connection.createStatement();
		} catch (Exception e) {
			throw new RuntimeException("建立Sqlite连接失败");
		}

	}

	/**
	 * @describe: 创建表
	 * @params: tableName: 要创建的表的名称 className：项目中Pojo的类名(需要注意的是该类名需要加上包名 如
	 *          com.xxx.xxx.pojo.xxx)
	 */
	public synchronized void update(String sql) {
		try {
			statement.executeUpdate(sql);
		} catch (Exception e) {
			logger.error("建表失败：" + e);
			throw new RuntimeException("sql执行失败");
		}
	}
	
	public synchronized ResultSet query(String sql) {
		try {
			return statement.executeQuery(sql);
		} catch (Exception e) {
			logger.error("查询失败：" + e);
			throw new RuntimeException("sql执行失败");
		}
	}

	/**
	 * @describe: 关闭链接
	 */
	public void endConnection() {
		try {
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void start(String devops, String filePathAndName) {
		DruidDataSource dataSource = new DruidDataSource();
		// 设置sqlite db文件存放基本目录
		String dbfile = filePathAndName;
		if(filePathAndName.contains("%s")) {
			dbfile = String.format(filePathAndName, Lambkit.context().resourceService().getWebRootPath());
			Printer.print(this, "db", "jdbc.url: " + dbfile);
		}
		dataSource.setUrl("jdbc:sqlite:" + dbfile);
		if(StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password))  {
			dataSource.setUsername(username);
			dataSource.setPassword(password);
		}
		HutoolDb htDb = new HutoolDb(dataSource, DRIVER_SQLLITE3);
		DbPool.add(devops, htDb);
	}

	public void stop(String devops) {
		DbPool.remove(devops);
	}
}
